package com.tenbit.pdt.ctl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.tenbit.com.vo.ErrorMsgVO;
import com.tenbit.pdt.svc.PDT1000SVCImpl;
import com.tenbit.pdt.vo.ProductInfoVO;
import com.tenbit.pdt.vo.ResultVO;

@Controller
public class PDT1000CTL {
	@Autowired
	private PDT1000SVCImpl pdt1000svcImpl;
	private Logger log=Logger.getLogger(this.getClass());
	
	public String doChgCalendarForm(String cal){
		String chgCal=null;
		
		if(cal.equals("")){
			chgCal="";
		}else{
			chgCal=cal.substring(0, 4)+"-"+cal.substring(4,6)+"-"+cal.substring(6);
			
		}
		
		return chgCal;
		
	}
	
	public Map<String, String> doRestoreView(HttpServletRequest request,MultipartFile file){
		//복원
		Map<String, String> returnMap=new HashMap<String, String>();
		
		returnMap.put("EMPLOYEE_ID",request.getParameter("employeeName"));
		returnMap.put("NAME",request.getParameter("name"));
		returnMap.put("DEPT_NAME",request.getParameter("dept_code"));
		returnMap.put("PRODUCT_CODE",request.getParameter("productCode"));
		returnMap.put("PRODUCT_NAME",request.getParameter("productName"));
		returnMap.put("ITEM_CODE",request.getParameter("itemCode"));
		returnMap.put("CATEGORY_NAME",request.getParameter("category"));
		returnMap.put("MANUFACTURE_CODE",request.getParameter("manufactureCode"));
		returnMap.put("PRODUCT_NUM",request.getParameter("productNum"));
		returnMap.put("STANDARD", request.getParameter("standard"));
		returnMap.put("UNIT_CODE",request.getParameter("unitCode"));
		returnMap.put("UNIT_PRICE",request.getParameter("unitPrice"));
		log.debug("doRestoreView"+file.getOriginalFilename());
		returnMap.put("FILENAME",file.getOriginalFilename());
		
		return returnMap;
	}
	@RequestMapping("/delPDTInfo.do")
	public ModelAndView delPDTInfo(ProductInfoVO productInfoVO){
		ModelAndView mv=new ModelAndView();
		
		pdt1000svcImpl.delProductInfo(productInfoVO);	
		mv.addObject("refersh", "<script>window.opener.location.reload(true);self.close();</script>");
		mv.setViewName("PDT1010P0");
		
		return mv;
	}
	@RequestMapping("/setPDTInfo.do")
	public ModelAndView setPDTInfo(ProductInfoVO productInfoVO,@RequestParam("file") MultipartFile file,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		StringBuffer buffer=new StringBuffer();
		ErrorMsgVO errorMsgVO = pdt1000svcImpl.doValidateForm(productInfoVO, file);
		
		if(errorMsgVO.isErrExist()){
			mv.addObject("errMsg", "<script>alert('"+errorMsgVO.getErrMsg()+"')</script>");
		}else{
			pdt1000svcImpl.setProductInfo(file, productInfoVO);
			buffer.append("<script>alert('수정이 성공했습니다.');")
		      .append("window.opener.location.reload(true);")
			  .append("self.close();")
			  .append("</script>");
			mv.addObject("successMsg", buffer);
		}
		
		//화면
		mv.addObject("CodeZip",pdt1000svcImpl.getCodeZipList());
		mv.addObject("itemName",pdt1000svcImpl.getItemNameList());
		//복원
		mv.addObject("productInfo",doRestoreView(request,file));
		mv.addObject("mode", "M");
		
		mv.setViewName("PDT1010P0");
		return mv;
	}
	
	@RequestMapping("/doDownLoad.do")
	public ModelAndView doDownLoad(@RequestParam("fileName") String fileName){
		log.debug("doDownLoad"+fileName);
		String path="C:\\TB\\WORKSHOP\\workspace\\tbworkshop\\WebContent\\upload\\";
		File file=new File(path+fileName);
		return new ModelAndView("download","downloadFile",file);
	}
	
	@RequestMapping("/doPDTInsView.do")
	public ModelAndView doPDTInsView(@RequestParam("mode") String mode,@RequestParam(value="product_num",required=false) String productNum){
		Logger log=Logger.getLogger(this.getClass());
		
		log.debug("doPDTInsView");
		
		ModelAndView mv = new ModelAndView();
		
		//화면
		mv.addObject("CodeZip",pdt1000svcImpl.getCodeZipList());
		mv.addObject("itemName",pdt1000svcImpl.getItemNameList());
		
		if(mode.equals("M")){
			mv.addObject("productInfo",pdt1000svcImpl.getProductInfo(productNum));
			mv.addObject("mode","M");
		}else if(mode.equals("I")){
			mv.addObject("mode","I");
		}else if(mode.equals("V")){
			mv.addObject("productInfo",pdt1000svcImpl.getProductInfo(productNum));
			mv.addObject("mode","V");
		}
		
		mv.setViewName("PDT1010P0");
		
		return mv;
	}
	
	@RequestMapping("/insPDTInfo.do")
	public ModelAndView insPDTInfo(ProductInfoVO productInfoVO,@RequestParam("file") MultipartFile file,HttpServletRequest request){
		log.debug("insPDTInfo "+productInfoVO);
		StringBuffer buffer=new StringBuffer();
		
		ModelAndView mv=new ModelAndView();
		ErrorMsgVO errorMsgVO = pdt1000svcImpl.doValidateForm(productInfoVO, file);
		
		if(errorMsgVO.isErrExist()){
			mv.addObject("errMsg", "<script>alert('"+errorMsgVO.getErrMsg()+"')</script>");
		}else{
			pdt1000svcImpl.insPDTInfo(file, productInfoVO);
			buffer.append("<script>alert('입력이 성공했습니다.');")
				  .append("window.opener.location.reload(true);")
				  .append("self.close();")
				  .append("</script>");
			mv.addObject("successMsg", buffer);
			
		}
		//화면
		mv.addObject("CodeZip",pdt1000svcImpl.getCodeZipList());
		mv.addObject("itemName",pdt1000svcImpl.getItemNameList());
		//복원
		mv.addObject("productInfo",doRestoreView(request,file));
		mv.addObject("mode", "I");
		
		mv.setViewName("PDT1010P0");
		return mv;
	}
	public Map<String, Object> parsingParaMap(Map<String, String[]> paraMap){
		Iterator<Entry<String, String[]>> it=paraMap.entrySet().iterator();
		Map<String, Object> map = new HashMap<String, Object>();
		
		while(it.hasNext()){
			Entry<String, String[]> entry = it.next();
			
			if(entry.getValue().length > 1){
				List<String> list= new ArrayList<String>();
				
				for (String str : entry.getValue()) {
					list.add(str);
				}
				
				map.put(entry.getKey(), list);
			}else{
				map.put(entry.getKey(), entry.getValue()[0]);
				
			}			
		}
		
		return map;
	}
	
	@RequestMapping("/doPDTMainView.do")
	public ModelAndView doPDTMainView(HttpServletRequest request,@RequestParam(value="page",required=false) String page){
		
		Logger log=Logger.getLogger(this.getClass());
		
		log.debug("ProductMain");
		
		ModelAndView mv = new ModelAndView();
		
		Map<String, Object> paraMap = parsingParaMap(request.getParameterMap());
		
		ErrorMsgVO errorMsgVO = pdt1000svcImpl.doValidateFormDate(paraMap);
		
		if(errorMsgVO.isErrExist()){
			mv.addObject("errMsg", "<script>alert('"+errorMsgVO.getErrMsg()+"')</script>");
			
			mv.addObject("initSaleSearch1",doChgCalendarForm(request.getParameter("saleSearch1"))); //조회:20010101->2001-01-01
			mv.addObject("initSaleSearch2",doChgCalendarForm(request.getParameter("saleSearch2")));
			
			//조회폼
			Map<String, String> searchMap=new HashMap<String, String>();
			searchMap.put("saleSearch1", request.getParameter("saleSearch1"));  //조회 : 20010101 -->20010101
			searchMap.put("saleSearch2", request.getParameter("saleSearch2"));
			searchMap.put("productName", request.getParameter("productName"));
			mv.addObject("searchMap",searchMap);
		}else{ 
			if(paraMap.get("saleSearch1") == null || paraMap.get("saleSearch2") == null){
				Calendar now = Calendar.getInstance();
				
				String saleSearch1 = ""+now.get(Calendar.YEAR)
						+( (now.get(Calendar.MONTH)+1)<10 ? "0"+(now.get(Calendar.MONTH)+1) : now.get(Calendar.MONTH)+1 )
						+"01";
				String saleSearch2 = ""+now.get(Calendar.YEAR)
						+( (now.get(Calendar.MONTH)+1)<10 ? "0"+(now.get(Calendar.MONTH)+1) : now.get(Calendar.MONTH)+1 )
						+( now.get(Calendar.DATE)<10 ? "0"+now.get(Calendar.DATE) : now.get(Calendar.DATE) );
				
				mv.addObject("initSaleSearch1",doChgCalendarForm(saleSearch1));
				mv.addObject("initSaleSearch2",doChgCalendarForm(saleSearch2));
				
				Map<String, String> searchMap=new HashMap<String, String>();
				searchMap.put("saleSearch1", saleSearch1);  //조회 : 20010101 -->20010101
				searchMap.put("saleSearch2", saleSearch2);
				searchMap.put("productName", request.getParameter("productName"));
				mv.addObject("searchMap",searchMap);
			}else{ //조회, 페이징
				//복원
				mv.addObject("initSaleSearch1",doChgCalendarForm(request.getParameter("saleSearch1"))); //조회:20010101->2001-01-01
				mv.addObject("initSaleSearch2",doChgCalendarForm(request.getParameter("saleSearch2")));
				
				//조회폼
				Map<String, String> searchMap=new HashMap<String, String>();
				searchMap.put("saleSearch1", request.getParameter("saleSearch1"));  //조회 : 20010101 -->20010101
				searchMap.put("saleSearch2", request.getParameter("saleSearch2"));
				searchMap.put("productName", request.getParameter("productName"));
				mv.addObject("searchMap",searchMap);
			}
			
			
		}
		mv.addObject("listPDT", pdt1000svcImpl.getProductInfoList(page, paraMap));
		mv.addObject("pageBean",pdt1000svcImpl.getPageBean(page, paraMap));
		
		mv.setViewName("PDT1000MO");
		
		return mv;
	}
	

	
	@RequestMapping("/getCategory.do")
	@ResponseBody
	public ResultVO getCategory(HttpServletRequest request){
		Logger log=Logger.getLogger(this.getClass());
		log.debug("getCategory "+request.getParameter("itemName"));
		
		ResultVO vo= new ResultVO();
	
		String codeName = pdt1000svcImpl.getCategoryName(request.getParameter("itemName"));
		vo.setStr(codeName);
		
		return vo;
	}
}
